package org.c797797ty.railway.service;
import org.c797797ty.railway.model.User;
import org.c797797ty.railway.util.DBUtil;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;
/**
 * @author C797797ty
 * @data 2025/11/3 14:16
 */

public class TicketService {
    private static final Scanner scanner = new Scanner(System.in);

    // 显示所有车票（按路线分组）
    public static void displayAllTickets() {
        try (ResultSet rs = DBUtil.executeQuery("SELECT * FROM tickets ORDER BY departure, time")) {
            System.out.println("\n===== 所有车票信息 =====");
            String currentRoute = "";
            while (rs.next()) {
                String route = rs.getString("departure") + "→" + rs.getString("destination");
                if (!route.equals(currentRoute)) {
                    System.out.println("\n=== " + route + " ===");
                    currentRoute = route;
                }
                System.out.printf("[%s] %s → %s | %s | %s | %s | ¥%.2f | 余票: %d\n",
                        rs.getString("ticket_id"),
                        rs.getString("departure"),
                        rs.getString("destination"),
                        rs.getString("time"),
                        rs.getString("time_slot"),
                        rs.getString("seat_class"),
                        rs.getDouble("price"),
                        rs.getInt("available_seats"));
            }
        } catch (SQLException e) {
            System.err.println("查询失败: " + e.getMessage());
        }
    }

    // 车票搜索
    public static void searchTickets() {
        System.out.print("出发地: ");
        String departure = scanner.nextLine();
        System.out.print("目的地: ");
        String destination = scanner.nextLine();

        try (ResultSet rs = DBUtil.executeQuery(
                "SELECT * FROM tickets " +
                        "WHERE departure = ? AND destination = ? " +
                        "ORDER BY time",
                departure, destination)) {

            System.out.println("\n===== 搜索结果 =====");
            boolean found = false;
            while (rs.next()) {
                found = true;
                System.out.printf("[%s] %s → %s | %s | %s | %s | ¥%.2f | 余票: %d\n",
                        rs.getString("ticket_id"),
                        rs.getString("departure"),
                        rs.getString("destination"),
                        rs.getString("time"),
                        rs.getString("time_slot"),
                        rs.getString("seat_class"),
                        rs.getDouble("price"),
                        rs.getInt("available_seats"));
            }
            if (!found) System.out.println("未找到匹配的车次");
        } catch (SQLException e) {
            System.err.println("搜索失败: " + e.getMessage());
        }
    }

    // 订票逻辑（支持座位选择）
    // 订票逻辑（支持座位选择）
    public static void bookTicket(User user) {
        System.out.print("出发地: ");
        String departure = scanner.nextLine();
        System.out.print("目的地: ");
        String destination = scanner.nextLine();

        // 显示可用车次
        System.out.println("\n===== 可用车次 =====");
        try (ResultSet rs = DBUtil.executeQuery(
                "SELECT * FROM tickets " +
                        "WHERE departure = ? AND destination = ? " +
                        "ORDER BY time",
                departure, destination)) {

            boolean hasTickets = false;
            while (rs.next()) {
                hasTickets = true;
                System.out.printf("[%s] %s → %s | %s | %s | %s | ¥%.2f | 余票: %d\n",
                        rs.getString("ticket_id"),
                        rs.getString("departure"),
                        rs.getString("destination"),
                        rs.getString("time"),
                        rs.getString("time_slot"),
                        rs.getString("seat_class"),
                        rs.getDouble("price"),
                        rs.getInt("available_seats"));
            }
            if (!hasTickets) {
                System.out.println("暂无可用车次");
                return;
            }
        } catch (SQLException e) {
            System.err.println("查询失败: " + e.getMessage());
            return;
        }

        // 选择车次和座位
        System.out.print("\n请输入要预订的车次ID: ");
        String ticketId = scanner.nextLine();
        System.out.print("请选择座位等级 (A/B/C/D/E/F): ");
        String selectedClass = scanner.nextLine().toUpperCase();

        try {
            DBUtil.beginTransaction();

            // 验证车次和座位
            try (ResultSet rs = DBUtil.executeQuery(
                    "SELECT * FROM tickets WHERE ticket_id = ? AND seat_class = ?",
                    ticketId, selectedClass)) {

                if (!rs.next()) {
                    System.out.println("无效的车次或座位等级");
                    DBUtil.rollbackTransaction();
                    return;
                }

                // 检查余票
                int availableSeats = rs.getInt("available_seats");
                if (availableSeats <= 0) {
                    System.out.println("该座位等级余票不足");
                    DBUtil.rollbackTransaction();
                    return;
                }

                // 更新余票
                DBUtil.executeUpdateInTransaction(
                        "UPDATE tickets SET available_seats = ? WHERE ticket_id = ?",
                        availableSeats - 1, ticketId);

                // 添加订单（关联座位等级）
                DBUtil.executeUpdateInTransaction(
                        "INSERT INTO user_tickets (user_id, ticket_id, seat_class) VALUES (?, ?, ?)",
                        user.getId(), ticketId, selectedClass);
            }

            DBUtil.commitTransaction();
            System.out.println("订票成功！");
        } catch (SQLException e) {
            DBUtil.rollbackTransaction();
            System.err.println("订票失败: " + e.getMessage());
        }
    }

    // 订单查看（显示座位等级）
    // 订单查看（显示座位等级）
    public static void viewMyTickets(User user) {
        if (user == null) {
            System.out.println("请先登录！");
            return;
        }

        try (ResultSet rs = DBUtil.executeQuery(
                "SELECT t.* " +
                        "FROM tickets t " +
                        "JOIN user_tickets ut ON t.ticket_id = ut.ticket_id " +
                        "WHERE ut.user_id = ?",
                user.getId())) {

            System.out.println("\n===== 我的订单 =====");
            boolean hasTickets = false;
            while (rs.next()) {
                hasTickets = true;
                System.out.printf("[%s] %s → %s | %s | %s | %s | ¥%.2f\n",
                        rs.getString("ticket_id"),
                        rs.getString("departure"),
                        rs.getString("destination"),
                        rs.getString("time"),
                        rs.getString("time_slot"),
                        rs.getString("seat_class"),
                        rs.getDouble("price"));
            }
            if (!hasTickets) System.out.println("您还没有订单");
        } catch (SQLException e) {
            System.err.println("查询订单失败: " + e.getMessage());
        }
    }

    // 退票逻辑
    public static void cancelTicket(User user) {
        viewMyTickets(user); // 显示当前订单

        if (user == null) return;

        System.out.print("\n请输入要退订的车票ID: ");
        String ticketId = scanner.nextLine();

        try {
            DBUtil.beginTransaction();

            // 检查订单归属
            try (ResultSet rs = DBUtil.executeQuery(
                    "SELECT * FROM user_tickets " +
                            "WHERE user_id = ? AND ticket_id = ?",
                    user.getId(), ticketId)) {

                if (!rs.next()) {
                    System.out.println("您没有这张车票！");
                    DBUtil.rollbackTransaction();
                    return;
                }

                // 删除订单
                DBUtil.executeUpdateInTransaction(
                        "DELETE FROM user_tickets " +
                                "WHERE user_id = ? AND ticket_id = ?",
                        user.getId(), ticketId);

                // 恢复余票
                try (ResultSet rsSeats = DBUtil.executeQuery(
                        "SELECT available_seats FROM tickets WHERE ticket_id = ?",
                        ticketId)) {

                    if (rsSeats.next()) {
                        int newSeats = rsSeats.getInt("available_seats") + 1;
                        DBUtil.executeUpdateInTransaction(
                                "UPDATE tickets SET available_seats = ? WHERE ticket_id = ?",
                                newSeats, ticketId);
                    }
                }
            }

            DBUtil.commitTransaction();
            System.out.println("退票成功！");
        } catch (SQLException e) {
            DBUtil.rollbackTransaction();
            System.err.println("退票失败: " + e.getMessage());
        }
    }



    /**
     * 帮他人购票功能
     */
    public static void bookTicketForOther(User currentUser) {
        if (currentUser == null) {
            System.out.println("请先登录！");
            return;
        }

        System.out.print("请输入被购票用户的用户名: ");
        String targetUsername = scanner.nextLine();

        // 查询目标用户是否存在
        User targetUser = UserService.getUserByUsername(targetUsername);
        if (targetUser == null) {
            System.out.println("用户不存在！");
            return;
        }

        System.out.print("出发地: ");
        String departure = scanner.nextLine();
        System.out.print("目的地: ");
        String destination = scanner.nextLine();

        // 显示可用车次
        System.out.println("\n===== 可用车次 =====");
        try (ResultSet rs = DBUtil.executeQuery(
                "SELECT * FROM tickets " +
                        "WHERE departure = ? AND destination = ? " +
                        "ORDER BY time",
                departure, destination)) {

            boolean hasTickets = false;
            while (rs.next()) {
                hasTickets = true;
                System.out.printf("[%s] %s → %s | %s | %s | %s | ¥%.2f | 余票: %d\n",
                        rs.getString("ticket_id"),
                        rs.getString("departure"),
                        rs.getString("destination"),
                        rs.getString("time"),
                        rs.getString("time_slot"),
                        rs.getString("seat_class"),
                        rs.getDouble("price"),
                        rs.getInt("available_seats"));
            }
            if (!hasTickets) {
                System.out.println("暂无可用车次");
                return;
            }
        } catch (SQLException e) {
            System.err.println("查询失败: " + e.getMessage());
            return;
        }

        // 选择车次
        System.out.print("请输入车票ID: ");
        String ticketId = scanner.nextLine();

        // 选择座位等级
        System.out.print("请选择座位等级 (一等座/二等座/商务座): ");
        String selectedClass = scanner.nextLine();

        try {
            DBUtil.beginTransaction();

            // 检查余票
            try (ResultSet rs = DBUtil.executeQuery(
                    "SELECT available_seats FROM tickets WHERE ticket_id = ?",
                    ticketId)) {

                if (!rs.next() || rs.getInt("available_seats") <= 0) {
                    System.out.println("该车次已无余票！");
                    DBUtil.rollbackTransaction();
                    return;
                }
            }

            // 获取车票详细信息用于消息通知
            String departureInfo = "";
            String destinationInfo = "";
            String timeInfo = "";
            String seatClassInfo = "";

            try (ResultSet rs = DBUtil.executeQuery(
                    "SELECT departure, destination, time, seat_class FROM tickets WHERE ticket_id = ?",
                    ticketId)) {
                if (rs.next()) {
                    departureInfo = rs.getString("departure");
                    destinationInfo = rs.getString("destination");
                    timeInfo = rs.getString("time");
                    seatClassInfo = rs.getString("seat_class");
                }
            }

            // 为被购票用户创建订单
            DBUtil.executeUpdateInTransaction(
                    "INSERT INTO user_tickets (user_id, ticket_id, seat_class) VALUES (?, ?, ?)",
                    targetUser.getId(), ticketId, selectedClass);

            // 更新余票
            DBUtil.executeUpdateInTransaction(
                    "UPDATE tickets SET available_seats = available_seats - 1 WHERE ticket_id = ?",
                    ticketId);

            DBUtil.commitTransaction();

            // 发送系统消息给被购票用户
            String message = String.format("【系统消息】 您已购买高铁票 ：%s到%s %s %s，   购票人：%s",
                    departureInfo, destinationInfo, timeInfo, seatClassInfo, currentUser.getUsername());
            MessageService.sendSystemMessage(targetUser.getId(), message);

            System.out.println("帮" + targetUsername + "购票成功！系统消息已发送。");
        } catch (SQLException e) {
            DBUtil.rollbackTransaction();
            System.err.println("购票失败: " + e.getMessage());
        }
    }


}